package com.longyi.tenant;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description 多租户处理类
 * @Date 2020-08-26 5:06 下午
 * @Author wuyanshen
 */
public class CommonTenantHandler implements TenantHandler {

    @Autowired
    private TenantProperties tenantProperties;


    @Override
    public Expression getTenantId(boolean where) {
        Integer tenantId = TenantHolder.getTenantId();
        if(ObjectUtil.isEmpty(tenantId)){
            return new LongValue(1);
        }else {
            return new LongValue(tenantId);
        }

    }

    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    @Override
    public boolean doTableFilter(String tableName) {

        // 判断是否开启多租户功能
        if(!tenantProperties.isEnable()){
            return true;
        }

        // 判断租户id是否为null，为null表示是租户系统管理员，可以看所有租户数据
        Integer tenantId = TenantHolder.getTenantId();
        if(ObjectUtil.isEmpty(tenantId)){
            return true;
        }

        // 判断需要忽略的表
        if (tenantProperties.getTables().contains(tableName)){
            return true;
        }

        return false;
    }
}
